//
//  ViewController.m
//  UIWebViewDemo
//
//  Created by Suns孙泉 on 14/12/3.
//  Copyright (c) 2014年 Suns. All rights reserved.
//

#import "ViewController.h"

@interface ViewController () <UIWebViewDelegate>

@property (nonatomic, retain) UIWebView *webView;

// 大仁哥"说"的"菊花"
@property (nonatomic, retain) UIActivityIndicatorView *actIV;

// 加载时的view
@property (nonatomic, retain) UIView *loadingView;

@end

@implementation ViewController

- (void)dealloc
{
    [_webView release];
    [_actIV release];
    [_loadingView release];
    [_str release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    self.webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    
    // 代理UIWebViewDelegate
    self.webView.delegate = self;
    [self.view addSubview:self.webView];
    
    // 请求URL
//    NSString *str = @"http://www.apple.com.cn";
    self.str = [self.str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:self.str];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
    
    // 加载请求
    [self.webView loadRequest:request];
    [_webView release];
    
    self.loadingView = [[UIView alloc] initWithFrame:self.view.bounds];
    self.loadingView.backgroundColor = [UIColor blackColor];
    
    // 设置成半透明
    self.loadingView.alpha = 0.5;
    [self.view addSubview:self.loadingView];
    [_loadingView release];
}

// 开始加载
- (void)webViewDidStartLoad:(UIWebView *)webView{
    
    self.actIV = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle: UIActivityIndicatorViewStyleWhite];
    self.actIV.frame = CGRectMake(0, 0, 32, 32);
    
    // 设置菊花在视图中心位置
    self.actIV.center = self.loadingView.center;
    [self.loadingView addSubview:self.actIV];
    
    // 菊花开始转动
    [self.actIV startAnimating];
    [_actIV release];
//    NSLog(@"startLoad");
}

// 加载完成
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    
    // 菊花停止转动
    [self.actIV stopAnimating];
    
    // 将载入时的view移除
    [self.loadingView removeFromSuperview];
//    NSLog(@"finishLoad");
}

// 加载失败
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    
    [self.actIV stopAnimating];
    [self.loadingView removeFromSuperview];
    NSLog(@"failLoadWithError: %@", error);
    // 加载失败提示
//    UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:@"提示" message:@"加载失败" delegate:self cancelButtonTitle:@"取消" otherButtonTitles: nil];
//    [alertV show];
//    [alertV release];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
